<template>
	<view style="position: relative;">
		<uv-swiper imgMode="heightFix" :height="555" :radius="0" :interval="6000" circular :duration="300" :list="bannerList" @click="bindSwiper" @change="e => current = e.current" :autoplay="true">
			<template v-slot:indicator>
				<view class="indicator">
					<view class="indicator__dot" v-for="(item, index) in bannerList" :key="index" :class="[index === current && 'indicator__dot--active']">
					</view>
				</view>
			</template>
		</uv-swiper>
		<view class="address-title-header">
			<uv-navbar bgColor="transparent" titleStyle="color:#000000;font-weight: bold;" title="城伴" :safeAreaInsetTop="true">
				<template v-slot:left>
					<view class="u-nav-slot">
						<view class="header" @click.stop="changeAddress">
							<view class="city">
								<image src="/static/images/address.png" mode="aspectFill"></image>
								<text class="city-name" v-if="address==''">定位中</text>
								<text class="city-name" v-if="address!=''">{{address}}</text>
							</view>
						</view>
					</view>
				</template>
			</uv-navbar>

		</view>
		<view class="search-box" :style="{ marginTop: (statusBarHeight+44+15) + 'px' }">
			<view class="search-item" @click="toSearch">
				<view class="search-scan" @click.stop="scanCodeHandle">
					<uv-icon name="scan" color="#000" size="28"></uv-icon>
				</view>
				<input type="text" placeholder-class="placeholder-style" placeholder-style="color:#ffffff" placeholder="输入关键词搜索" disabled />
				<view class="search-btn">
					<image src="/static/images/search.png" mode="aspectFill"></image>
				</view>
			</view>
		</view>
		<view class="active-box padding_30">
			<view class="active-item" @click="toTask">
				<view class="left-text">
					<view class="title">
						<image class="left-img" src="../../static/images/left_title.png" mode="aspectFill"></image>
						<text class="middle-title">联结找伴</text>
						<image class="right-img" src="../../static/images/right_title.png" mode="aspectFill"></image>
					</view>
					<view class="sub-title">
						找对的伴，攒好的局！
					</view>
				</view>
				<view class="right-image">
					<image src="@/static/images/task.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="active-item" @click="toGroup">
				<view class="left-text">
					<view class="title">
						<image class="left-img" src="../../static/images/left_title.png" mode="aspectFill"></image>
						<text class="middle-title">组局活动</text>
						<image class="right-img" src="../../static/images/right_title.png" mode="aspectFill"></image>
					</view>
					<view class="sub-title">
						局对了，生活就对了！
					</view>
				</view>
				<view class="right-image">
					<image src="@/static/images/group.png" mode="aspectFill"></image>
				</view>
			</view>
		</view>
		<view class="invite-banner" v-if="bannerflowList.length>0">
			<uv-swiper height="90" :list="bannerflowList" @click="toLinkUrl"></uv-swiper>
		</view>
		<view class="select-active padding_30">
			<view class="title">
				<image class="left-img" src="../../static/images/left_title.png" mode="aspectFill"></image>
				<text class="middle-title">精选活动</text>
				<image class="right-img" src="../../static/images/right_title.png" mode="aspectFill"></image>
			</view>
			<ActiveList :list="activeList" ishome="home"></ActiveList>
			<view class="footer-img">
				<image src="../../static/images/footer.png" mode="aspectFill"></image>
			</view>
		</view>
		<cityPicker :column="column" :addressList="mapDataList" :default-value="defaultValue" :mask-close-able="maskCloseAble" @confirm="addressConfirm" @cancel="visible=false" :visible="visible" />
		<tabbar :current="0"></tabbar>

	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow,
		onPullDownRefresh,
		onReachBottom,
		onReady
	} from "@dcloudio/uni-app";
	import {
		reactive,
		ref,
		watch
	} from 'vue'
	import { getCityIdAPI } from '@/api/user.js'
	import cityPicker from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker'
	import {
		throttle
	} from "@/utils/utils.js"
	import {
		useUserStore
	} from '@/store/modules/user.js'
	const userstore = useUserStore()
	import {
		useActiveStore
	} from '@/store/modules/active.js'
	const activeStore = useActiveStore()
	import tabbar from '@/components/tabbar/tabbar' //引用组件中的tabbar
	import ActiveList from "@/components/ActiveList.vue";
	const current = ref(0)
	// 初始化顶部距离为0
	const statusBarHeight = ref(0)
	const btnHeight = ref(0)
	const page = ref(1)
	const loadStatus = ref('loadmore')
	const activeList = ref([])
	const bannerList = ref([])
	const bannerflowList = ref([])
	const banner = ref([])
	const address = ref('')
	// 控制选择器显示和隐藏
	const visible = ref(false)
	// 点击模态框是否关闭弹框
	const maskCloseAble = ref(true)
	// 初始地区编码（例:或者['河北省','唐山市','丰南区']）
	const defaultValue = ref('')
	// 2是省市两列选择；3是省市区三列选择
	const column = ref(2)
	const mapDataList = ref([])
	const toTask = () => {
		uni.navigateTo({
			url: '/pages/task/index'
		})
	}
	const toSearch = throttle(() => {
		uni.navigateTo({
			url: '/pages/search/index'
		})
	}, 500)
	const bindSwiper = (e) => {
		console.log(banner.value[e].path)
		if (banner.value[e].path != "") {
			if (isExternalLink(banner.value[e].path)) {
				uni.navigateTo({
					url: `/pages/webView/webView?path=${banner.value[e].path}`
				})
			} else {
				uni.navigateTo({
					url: `/${banner.value[e].path}`
				})
			}
		}
	}
	const toGroup = () => {
		uni.navigateTo({
			url: '/pages/group/index'
		})
	}

	const isExternalLink = (url) => {
		// 判断是否以 http:// 或 https:// 开头
		const isExternal = /^(http|https):\/\//i.test(url);

		return isExternal;
	}
	const  getUrlParams = (url) => {
		const params = {};
		const queryString = url.split("?")[1];
		if (queryString) {
			const keyValuePairs = queryString.split("&");
			keyValuePairs.forEach((pair) => {
				const [key, value] = pair.split("=");
				params[decodeURIComponent(key)] = decodeURIComponent(value);
			});
		}
		return params;
	};
	const scanCodeHandle = () => {
		
	  uni.scanCode({
	    onlyFromCamera: true,
	    success: (res) => {
	      if (res.scanType == "QR_CODE") {
			setTimeout(()=>{
				uni.navigateTo({
					url:'/'+ res.result
				})
			},200)
	      } else {
			
	        // uni.Toast("无效码")
	      }
	    }
	  });
	}

	onLoad(async () => {
		// let token=uni.getStorageSync('token')
		// if(token){
		// 	uni.hideTabBar()
		// 	// 获取系统信息
		// 	uni.getSystemInfo({
		// 		success: (res) => {
		// 			// console.log(res)
		// 			if (res.safeArea && res.safeArea.top > 0) {
		// 				statusBarHeight.value = res.safeAreaInsets.top;
		// 				btnHeight.value = uni.getMenuButtonBoundingClientRect().height
		// 			} else {
		// 				statusBarHeight.value = 24;
		// 			}
		// 		}
		// 	})
		// 	getConfigData()
		// 	MapDataList()
		// }
		uni.hideTabBar()
		// 获取系统信息
		uni.getSystemInfo({
			success: (res) => {
				// console.log(res)
				if (res.safeArea && res.safeArea.top > 0) {
					statusBarHeight.value = res.safeAreaInsets.top;
					btnHeight.value = uni.getMenuButtonBoundingClientRect().height
				} else {
					statusBarHeight.value = 24;
				}
			}
		})
		getConfigData()
		MapDataList()
	})
	onReady(() => {
		uni.getLocation({
			type: 'wgs84',
			success: (res) => {
				// console.log(33,res);
				uni.setStorageSync('longitude', res.longitude)
				uni.setStorageSync('latitude', res.latitude)
				// console.log(res.longitude,res.latitude)
				getAddress(res.latitude, res.longitude)
			},
			fail: (err) => {
				uni.$uv.toast('定位失败')
			}
		});

	})
	onShow(() => {
		address.value = uni.getStorageSync('cityName')
	})
	watch(() => address.value, (newValue, oldValue) => {
		if (newValue) {
			if (address.value != '') {
				console.log(newValue, '地址变了~')
				page.value = 1
				activeList.value = []
				selectedActiveList()
			}

		}
	}, { immediate: false })
	onPullDownRefresh(() => {
		getConfigData()
		page.value = 1
		activeList.value = []
		selectedActiveList()
		setTimeout(() => {
			uni.stopPullDownRefresh()
		}, 600)
	})
	onReachBottom(() => {
		if (loadStatus.value == 'nomore') {
			return
		}
		page.value++
		selectedActiveList()
	})
	// 地理位置逆解析
	const getAddress = (latitude, longitude) => {

		uni.request({
			url: `https://apis.map.qq.com/ws/geocoder/v1?location=${latitude},${longitude}&key=BLWBZ-5A6CZ-SZ3XY-7QWE6-Z3X63-CGF5W&get_poi=1`,
			success: (res) => {
				let result = res.data.result.address_component
				// address.value = result.city
				uni.setStorageSync('cityName', result.city)
				address.value = uni.getStorageSync('cityName')

				getCityIdAPI({ lat: latitude, lng: longitude }).then(res => {
					uni.setStorageSync('cityId', res.data.city_id)
					page.value = 1
					activeList.value = []
					selectedActiveList()
				})
			}
		})
	}
	// const openAddressPopup = async () => {
	// 	let res = await userstore.getMapDataList()
	// 	if (res.code == 200) {
	// 		mapDataList.value = res.data
	// 		visible.value = true
	// 	}
	// }
	// 确认地址
	const addressConfirm = (val) => {
		console.log(val)
		// address.value = val.cityName
		uni.setStorageSync('cityName', val.cityName)
		uni.setStorageSync('cityId', val.cityCode)
		address.value = uni.getStorageSync('cityName')
		visible.value = false
	}
	// 改变当前位置
	const changeAddress = async () => {
		if (mapDataList.value.length) {
			visible.value = true
		} else {
			let res = await userstore.getMapDataList()
			if (res.code == 200) {
				mapDataList.value = res.data
				visible.value = true
			}
		}
		// uni.chooseLocation({
		// 	success: (res)=> {
		// 		uni.setStorageSync('longitude', res.longitude)
		// 		uni.setStorageSync('latitude', res.latitude)
		// 		getAddress(res.latitude,res.longitude)
		// 	}
		// });

	}
	const MapDataList = async () => {
		let res = await userstore.getMapDataList()
		if (res.code == 200) {
			mapDataList.value = res.data
		}
	}
	// 获取文件域名
	const getConfigData = async () => {
		let res = await userstore.getConFig({
			type: 'getBaseUrl'
		})
		if (res.code == 200) {
			uni.setStorageSync('baseUrl', res.data.content)
			getBannerList()
			getBannerfolwList()
		}
	}
	// 获取banner图
	const getBannerList = async () => {
		let res = await activeStore.getBannerList({
			position: 2
		})
		if (res.code == 200) {
			bannerList.value = res.data.map(item => {
				return uni.getStorageSync('baseUrl') + item.image
			})
			banner.value = res.data
		}
	}
	const getBannerfolwList = async () => {
		let res = await activeStore.getBannerList({
			position: 6
		})
		if (res.code == 200) {
			bannerflowList.value = res.data.map(item => {
				return uni.getStorageSync('baseUrl') + item.image
			})
			banner.value = res.data
		}
	}
	// 精选活动列表
	const selectedActiveList = async () => {
		let params = {
			lat: uni.getStorageSync('latitude'),
			lng: uni.getStorageSync('longitude'),
			page: page.value,
			city_id: uni.getStorageSync('cityId')
		}
		loadStatus.value = 'loading'
		let res = await activeStore.selectedActiveList(params)
		if (res.code == 200 && res.data) {
			activeList.value = activeList.value.concat(res.data.data)
			// 判断是否还有数据
			if (res.data.current_page >= res.data.last_page) {
				loadStatus.value = 'nomore'
			} else {
				loadStatus.value = 'loadmore'
			}
		} else {
			loadStatus.value = 'nomore'
		}
	}
</script>
<style>
	page {
		background: #F6F6F6;
		padding-bottom: 60rpx;
	}
</style>
<style lang="scss">
	.invite-banner {
		margin: auto;
		margin-top: 30rpx;
		width: 690rpx;
		height: 180rpx;
	
		image {
			width: 100%;
			height: 100%;
		}
	}
	.placeholder-style {
		color: #fff;
		font-size: 28rpx;
	}

	@mixin flex($direction: row) {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: $direction;
	}

	.indicator {
		@include flex(row);
		justify-content: center;

		&__dot {
			height: 6rpx;
			width: 32rpx;
			background-color: #D8D8D8;
			margin: 0rpx 5rpx;
			transition: background-color 0.3s;

			&--active {
				background-color: #FE3052;
			}
		}
	}

	.padding_30 {
		padding: 0 30rpx;
	}

	.address-title-header {
		// position: absolute;
		// top: 0;
		// left: 0;
		// width: 100%;

		.header {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 88rpx !important;

			.city {
				display: flex;
				align-items: center;

				image {
					width: 28rpx;
					height: 28rpx;
				}

				.city-name {
					width: 260rpx;
					margin-left: 8rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 28rpx;
					color: #000000;
					font-style: normal;
					text-transform: none;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}

			.title {
				font-family: PingFang SC, PingFang SC;
				font-weight: bold;
				font-size: 32rpx;
				color: #FFFFFF;
				text-align: center;
				font-style: normal;
				text-transform: none;
			}
		}


	}

	.search-box {
		position: fixed;
		top: 0;
		z-index: 1;
		width: 100%;

		.search-item {
			display: flex;
			align-items: center;
			margin: auto;
			width: 690rpx;
			background-color: rgba(255, 255, 255, 0.3);
			border-radius: 40rpx 40rpx 40rpx 40rpx;
			padding: 8rpx;
			color: #000;
			border: 1px solid #000;
			input {
				width: 594rpx;
				margin-left: 36rpx;
				color: #fff;
			}

			.search-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 96rpx;
				height: 64rpx;
				background: #222222;
				border-radius: 32rpx 32rpx 32rpx 32rpx;

				image {
					width: 32rpx;
					height: 32rpx;
				}
			}
		}
	}

	.active-box {
		display: flex;
		align-items: center;
		justify-content: space-around;
		margin: 40rpx 0;

		.active-item {
			position: relative;
			display: flex;
			align-items: center;
			justify-content: space-around;
			height: 152rpx;
			// width: 332rpx;
			padding: 0 20rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 0rpx 20rpx 2rpx rgba(0, 0, 0, 0.03);
			border-radius: 20rpx 20rpx 20rpx 20rpx;

			.left-text {
				display: flex;
				justify-content: start;
				flex-direction: column;
				height: 152rpx;

				.title {
					padding-top: 30rpx;

					.left-img {
						width: 30rpx;
						height: 24rpx;
					}

					.middle-title {

						font-family: PingFang SC, PingFang SC;
						font-weight: 800;
						font-size: 32rpx;
						color: #222222;
						text-align: left;
					}

					.right-img {
						width: 24rpx;
						height: 24rpx;
					}
				}

				.sub-title {
					position: absolute;
					bottom: 20rpx;
					left: 20rpx;

					z-index: 2;
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 26rpx;
					color: #666666;
				}
			}

			.right-image {
				image {
					width: 100rpx;
					height: 100rpx;
				}
			}
		}
	}

	.select-active {
		.title {
			padding-top: 30rpx;

			.left-img {
				width: 30rpx;
				height: 24rpx;
			}

			.middle-title {

				font-family: PingFang SC, PingFang SC;
				font-weight: 800;
				font-size: 32rpx;
				color: #222222;
				text-align: left;
			}

			.right-img {
				width: 24rpx;
				height: 24rpx;
			}
		}


	}

	.footer-img {
		width: 510rpx;
		height: 90rpx;
		margin: 60rpx auto 140rpx auto;

		image {
			width: 100%;
			height: 100%;
		}
	}
</style>